<template>
    <div class="lottery-list" v-loading="loading">
        <div class="lottery-option-box">
            <div class="input-box">
                <span class="input-title" style="margin-left:0px;">期数</span>
                <el-input
                    placeholder="请输入期数"
                    @keyup.enter.native="selectChange"
                    style="width:140px;"
                    clearable
                    v-model.trim="paramsList.phase">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <span class="input-title">是否兑换</span>
                <el-select @change="selectChange" style="width:120px;" v-model="paramsList.exchangeStatus">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="是" :value="1"></el-option>
                    <el-option label="否" :value="0"></el-option>
                </el-select>
                <span class="input-title">关联游戏</span>
                <el-select
                    style="width:180px"
                    v-model="paramsList.gameId"
                    clearable
                    :loading="gameLoading"
                    @change="selectChange"
                    placeholder="请输入并选择游戏">
                    <el-option
                        v-for="item in gameList"
                        :key="item.gameid"
                        :label="item.appName"
                        :value="item.gameid">
                            <span style="float: left">
                                <span>{{ item.appName }}</span>
                                <span v-if="item.status === -1" style="color:red;font-size:12px;margin:0 5px;">下架</span>
                            </span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.gameid }}</span>
                    </el-option>
                </el-select>
                <span class="input-title">兑换码</span>
                <el-input
                    placeholder="请输入兑换码"
                    @keyup.enter.native="getList(1)"
                    style="width:200px;"
                    clearable
                    v-model.trim="paramsList.cdKey">
                </el-input>
            </div>
            <div class="input-box">
                <span class="input-title" style="margin-left:0px;">状态</span>
                <el-select @change="selectChange" style="width:140px;" v-model="paramsList.rewardStatus">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="进行中" :value="0"></el-option>
                    <el-option label="已开奖" :value="2"></el-option>
                    <el-option label="未上架" :value="-1"></el-option>
                </el-select>
                <span class="input-title">发放形式</span>
                <el-select
                    @change="selectChange"
                    style="width:120px;"
                    v-model="paramsList.exchangeType">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="微信转账" :value="1"></el-option>
                    <el-option label="游戏赠送" :value="2"></el-option>
                    <el-option label="金币赠送" :value="3"></el-option>
                </el-select>
                <span class="input-title">开奖时间</span>
                <el-date-picker
                    @change="getList(1, 10)"
                    v-model="date"
                    :clearable="true"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </div>
            <div class="input-box">
                <span class="input-title" style="margin-left:0px;">兑换时间</span>
                <el-date-picker
                    @change="getList(1, 10)"
                    v-model="exchangeDate"
                    :clearable="true"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
                <el-button type="primary" class="btn" style="margin-left: 10px;" @click="getList(1)">查询</el-button>
                <el-button type="success" class="btn" @click="goCreate">新增抽奖</el-button>
                <el-button type="warning" class="btn" @click="exportExcel">导出</el-button>
            </div>
        </div>

        <div class="table-box">
            <el-table :data="tableData" ref="table" @sort-change="sortChange" border style="width: 100%">
                <el-table-column min-width="120" prop="phase" label="期数"></el-table-column>
                <el-table-column min-width="190" label="兑换码">
                    <template slot-scope="scope">
                        <div>{{ scope.row.key || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" prop="maxReward" label="最高奖项"></el-table-column>
                <el-table-column min-width="100" prop="currentTimes" label="开奖次数"></el-table-column>
                <el-table-column min-width="100" label="参与人数">
                    <template slot-scope="scope">
                        <div>{{ scope.row.joinUserCount || 0 }}</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" label="关联游戏">
                    <template slot-scope="scope">
                        <div v-for="(item, index) in scope.row.luckyGameInfoList" :key="index">
                            <span v-if="index > 0">, {{ item.gameName }}</span>
                            <span v-else>{{ item.gameName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column width="180" label="开奖时间">
                    <template slot-scope="scope">
                        <div>{{ scope.row.endTime }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="开奖状态" width="100">
                    <template slot-scope="scope">
                        <div style="color: #67C23A;" v-if="scope.row.rewardStatus === 2">
                            <span>已开奖</span>
                        </div>
                        <div style="color:#F56C6C;" v-if="scope.row.rewardStatus === 0">
                            <span>未开奖</span>
                        </div>
                        <div style="color:#F56C6C;" v-if="scope.row.rewardStatus === -1">
                            <span>未上架</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" label="中奖用户">
                    <template slot-scope="scope">
                        <div>{{ scope.row.userName || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" prop="status" label="是否已兑换">
                    <template slot-scope="scope">
                        <div style="color: #67C23A;" v-if="scope.row.exchangeStatus === 0">
                            <span class="point"></span>
                            <span>可兑换</span>
                        </div>
                        <div style="color:#F56C6C;" v-else-if="scope.row.exchangeStatus === 1">
                            <div class="point red-point"></div>
                            <span>已兑换</span>
                        </div>
                        <div v-else>
                            <span>-</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column min-width="100" label="发放形式">
                    <template slot-scope="scope">
                        <div v-if="scope.row.exchangeType === 1">微信转账</div>
                        <div v-if="scope.row.exchangeType === 2">游戏赠送</div>
                        <div v-if="scope.row.exchangeType === 3">金币赠送</div>
                        <div v-if="!scope.row.exchangeType">-</div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <div v-if="scope.row.status > 0 && !scope.row.currentTimes && scope.row.rewardStatus !== 2">
                            <el-button @click="changeStatus(scope.row, -1)" type="text" size="small" style="color:#909399;">下架</el-button>
                        </div>
                        <div v-if="scope.row.status < 2">
                            <el-button @click="changeStatus(scope.row, 2)" type="text" size="small" style="color:#67C23A;">上架</el-button>
                        </div>
                        <div>
                            <el-button v-if="scope.row.exchangeStatus === 0" @click="goExchange(scope.row)" type="text" size="small" style="color:#E6A23C;">兑换</el-button>
                        </div>
                        <div>
                            <el-button @click="goLotteryDetail(scope.row.activityId)" type="text" size="small">查看详情</el-button>
                        </div>
                        <div>
                            <el-button @click="changeStatus(scope.row, -2)" type="text" size="small" style="color:#F56C6C;">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="tools">
            <p>抽奖总额：{{ this.stampsCount }}点券</p>
            <el-pagination
                @size-change="sizeChange"
                @current-change="pageChange"
                :current-page="pageNum"
                :page-sizes="_pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="dialogTit" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <div class="dialog-slot">
                <div class="dialog-item">
                    <span style="margin-right: 10px">发放形式：</span>
                    <el-select v-model="exchangeParams.exchangeType" placeholder="请选择发放形式">
                        <el-option label="微信转账" :value="1"></el-option>
                        <el-option label="游戏赠送" :value="2"></el-option>
                        <el-option label="金币赠送" :value="3"></el-option>
                    </el-select>
                </div>
                <div>
                    <span style="margin-right: 10px">发放数量：</span>
                    <el-input
                        placeholder="请输入发放数量"
                        @keyup.enter.native="getList(1)"
                        style="width:200px;"
                        clearable
                        v-model.trim="exchangeParams.number">
                    </el-input>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'
export default {
    data () {
        return {
            paramsList: {
                phase: '',
                rewardStatus: '',
                endTime: null,
                exchangeStatus: null,
                gameId: '',
                activityId: ''
            },
            date: [],
            exchangeDate: [],
            exchangeParams: {},
            stampsCount: 0,
            dialogTit: '',
            tableData: [],
            pageNum: 1,
            pageSize: this._pageSize,
            total: 0,
            loading: false,
            dialogVisible: false,
            gameLoading: false, // 查询游戏的loading
            gameList: [] // 游戏列表
        }
    },
    activated () {
        if (location.host.indexOf('work.duodian.cn') !== -1) {
            this.gameList = this._proGameList
        } else {
            this.gameList = this._devGameList
        }
        this.getList(this.pageNum)
    },
    methods: {
        // 获取列表
        async getList (pageNum) {
            if (this.loading) return
            if (this.paramsList.endTime) this.paramsList.endTime = formatDate(this.paramsList.endTime, 'YYYY-MM-DD') + ' 23:59:59'
            this.pageNum = pageNum
            this.loading = true
            let params = {
                pageNum: pageNum,
                pageSize: this.pageSize
            }
            this.paramsList.startTime = ''
            this.paramsList.endTime = ''
            this.paramsList.fromDate = ''
            this.paramsList.endDate = ''
            if (this.date && this.date.length) {
                this.paramsList.startTime = this.date[0] + ' 00:00:00'
                this.paramsList.endTime = this.date[1] + ' 23:59:59'
            }
            if (this.exchangeDate && this.exchangeDate.length) {
                this.paramsList.fromDate = this.exchangeDate[0] + ' 00:00:00'
                this.paramsList.endDate = this.exchangeDate[1] + ' 23:59:59'
            }

            params = Object.assign(params, this.paramsList)
            let res = await this.$http.get('/lottrey/selectLuckyActivityList', { params })
            if (res.code === '0') {
                this.stampsCount = res.data.stampsCount
                res.data.luckyActivityListVoList.map(item => {
                    item.endTime = formatDate(item.endTime, 'YYYY-MM-DD HH:MM:SS')
                })
                this.tableData = res.data.luckyActivityListVoList
                this.total = res.count
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.loading = false
        },
        // 后端排序
        sortChange ({ column, prop, order }) {
            this.sort = order || ''
            // 如果没有 sort prop 置为空
            if (!this.sort) {
                this.type = ''
            } else {
                this.type = prop
            }
            this.getList(1)
        },
        selectChange () {
            this.type = ''
            this.sort = ''
            this.$refs.table.clearSort()
            this.getList(1)
        },
        // 页码切换
        sizeChange (val) {
            this.pageNum = 1
            this.pageSize = val
            this.getList(1)
        },
        // 页容切换
        pageChange (val) {
            this.pageNum = val
            this.getList(this.pageNum)
        },
        // 查询游戏
        filterMethod (res) {
            clearTimeout(this.timerId)
            if (!res) {
                this.gameLoading = false
                return
            }
            this.gameLoading = true
            this.timerId = setTimeout(() => {
                this.getgameList(res)
            }, 1000)
        },
        async getgameList (keyword) {
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 100
            }
            let res = await this.$http.post('/home/findGames', params)
            if (res.code === '0') {
                this.gameList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },
        changeStatus (item, status) {
            if (status === -2) {
                this.$confirm(`是否删除期数为${item.phase}的活动?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.updateAct(item, status)
                })
            } else {
                this.updateAct(item, status)
            }
        },
        updateAct (item, status) {
            this.$http.post('/lottrey/updateActivityStatus', {
                activityId: item.activityId,
                status
            }).then(res => {
                if (res.code === '0') {
                    let message = status === -1 ? '下架成功' : '上架成功'
                    item.status = status > -1 ? 2 : -1
                    if (status === -2) {
                        message = '删除成功'
                        this.getList(1)
                    }
                    this.$message({
                        type: 'success',
                        message
                    })
                } else if (res.code === '80011') {
                    this.$message({
                        type: 'warning',
                        message: '无权限操作'
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        goExchange (item) { // 兑换
            this.dialogTit = `该用户的兑换码是${item.key}`
            this.exchangeParams = {
                id: item.exchangeId
            }
            this.dialogVisible = true
            this.currentItem = item
        },
        dialogSure () {
            this.$confirm(`是否兑换?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.post('/lottrey/confirmExchange', this.exchangeParams).then(res => {
                    if (res.code === '0') {
                        this.currentItem.exchangeStatus = 1
                        this.currentItem.exchangeType = this.exchangeParams.exchangeType
                        this.dialogVisible = false
                        this.$message({
                            type: 'success',
                            message: '兑换成功'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消兑换'
                })
            })
        },
        toGame (id) {
            const { href } = this.$router.resolve({
                path: '/game/gameDetail',
                query: {
                    id
                }
            })
            window.open(href, '_blank')
        },
        // 查看碎片详情
        goLotteryDetail (id) {
            this.$router.push({
                path: '/lottery/detail',
                query: { id }
            })
        },
        exportExcel () {
            this.$confirm(`是否导出全部抽奖数据?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let params = {
                    pageNum: 1,
                    pageSize: 999
                }
                params = Object.assign(params, this.paramsList)
                this.$http.post('/lottrey/exportLuckyActivityList', params, {
                    responseType: 'arraybuffer'
                }).then(res => {
                    const aLink = document.createElement('a')
                    let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
                    aLink.href = URL.createObjectURL(blob)
                    aLink.setAttribute('download', '抽奖数据' + '.xlsx') // 设置下载文件名称
                    aLink.click()
                })
            })
        },
        // 查看游戏详情
        goCreate () {
            this.$router.push({ path: '/lottery/create' })
        },
        handleClose (done) {
            done()
        }
    },
    filters: {
        timeInit (val) {
            if (val) {
                return formatDate(val, 'YYYY-MM-DD HH:MM:SS')
            } else {
                return '至今'
            }
        }
    }
}
</script>

<style lang="scss" scoped>
    .lottery-list {
        .lottery-option-box {
            min-width: 800px;
        }
        .input-box {
            margin-top: 10px;
            font-size: 13px;
            font-weight: 500;
            .input-title {
                margin: 0 10px 0 20px;
            }
            .btn {
                margin-top: 10px;
                margin-left: 10px;
            }
        }

        .table-box {
            margin: 20px 0;
            .cover {
                width: 80px;
                height: 80px;
                > img {
                    width: 100%;
                    height: 100%;
                }
            }
            .desc {
                overflow: hidden;
                line-height: 20px;
                -webkit-line-clamp: 5;
                -webkit-box-orient: vertical;
                display: -webkit-box;
                height: 100px;
            }
            .user-icon {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                margin-right: 5px;
                vertical-align: top;
            }
            .table-btn {
                cursor: pointer;
                color: #409EFF;
                font-size: 13px;
                font-weight: 500;
                &:hover {
                    text-decoration: underline;
                }
            }
            .point {
                display:inline-block;
                width:10px;
                height:10px;
                border-radius: 50%;
                background-color:#67C23A;
                margin-right:3px;
            }
            .red-point {
                background-color: #F56C6C;
            }
        }

        .tools {
            padding-right: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            p {
                font-size: 13px;
                color: #606266;
            }
        }
    }
    .dialog-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        .dialog-item {
            margin-bottom: 20px;
        }
    }
</style>
